package com.wonders.frame.chron.controller.summary;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wonders.frame.chron.controller.BasicChronController;
import com.wonders.frame.chron.model.bo.Card;
import com.wonders.frame.chron.model.bo.Catalog;
import com.wonders.frame.chron.model.bo.Summary;
import com.wonders.frame.chron.model.vo.CatalogVo;
import com.wonders.frame.chron.service.catalog.CatalogService;
import com.wonders.frame.chron.service.summary.SummaryService;
import com.wonders.frame.chron.util.FreeMarkerUtils;
import com.wonders.frame.chron.util.StringUtil;
import com.wonders.frame.core.model.IDefaultModel;
import com.wonders.frame.core.model.vo.RelatedNode;
import com.wonders.frame.core.model.vo.ReturnObj;
import com.wonders.frame.core.model.vo.SingleQueryParams;
import com.wonders.frame.core.utils.ReflectUtil;
import com.wonders.frame.core.utils.SingleParamsConvertUtil;

@Controller
@RequestMapping("/summary")
public class SummaryController extends BasicChronController<Summary> {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@RequestMapping(value={"/create"})
	public String create(HttpServletRequest request)
	{
		String[] cardIds = request.getParameterValues("cardCheckbox");
		List<Integer> cardIdList = new ArrayList<Integer>(); 
		for(String id : cardIds){
			cardIdList.add(Integer.valueOf(id));
		}
		
        Object rs = ReflectUtil.executeMethod("card", "findByIds", 
                new Class[] { Iterable.class }, new Object[] { cardIdList });
        List<Card> cardList = (List<Card>)rs;

        request.setAttribute("cardList", cardList);
        request.setAttribute("cardIds", StringUtils.join(cardIds, ","));
		return "summary/summaryAdd";
	}

	@RequestMapping(value={"/doDel/{id}"}, method={org.springframework.web.bind.annotation.RequestMethod.DELETE})
	@ResponseBody
	public void doDel(@PathVariable("id") String id){
		summaryService.delete(Integer.valueOf(id));
	}	
	
	@Autowired
	SummaryService summaryService;
	@Autowired
	private CatalogService catalogService;
	
	/**
	 * 导出多张长编
	 * @param id
	 * @param type
	 * @param sortField
	 * @param sortAsc
	 * @param neededObj
	 * @param lv
	 * @param ticket
	 * @param resourceType
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exportSummarys/{ids}")
	@ResponseBody
	public String exportSummarys(
			@PathVariable("ids") String ids,
			@RequestParam(value = "type", required = false, defaultValue = "") String type,
			@RequestParam(value = "sortField", required = false, defaultValue = "") String sortField,
			@RequestParam(value = "sortAsc", required = false, defaultValue = "asc") String sortAsc,
			@RequestParam(value = "objFilter", required = false, defaultValue = "") String neededObj,
			@RequestParam(value = "lv", required = false, defaultValue = "-1") int lv,
			@RequestParam(value = "ticket", required = true) String ticket,
			@RequestParam(value = "resourceType", required = true) String resourceType,
			HttpServletRequest request, HttpServletResponse response){
		
		/** 模板引擎所需要的数据Map */
		Map<String, Object> templateData = new HashMap<String, Object>();
		// 查询该长编的父级节点
		SingleQueryParams sqp = SingleParamsConvertUtil.getQueryParams(this.getEntityClass(), request);
		sqp.addSort("operateTime", "asc");
		sqp.addData("status", "finish");
		sqp.addData("id_in", ids);
		ReturnObj<List<IDefaultModel>> returnObj = getBasicCrudService().find(sqp);
		if (!returnObj.getInfo().getSuccess()) 
			return null;
		List<CatalogVo> catalogVos=new ArrayList<CatalogVo>();
		for (IDefaultModel data : returnObj.getData()) {
			Summary s=(Summary) data;
			//查询该长编父节点
			ReturnObj<List<RelatedNode<IDefaultModel, Integer>>> parentNode = getParentNode(s.getId(), sortField, sortAsc, neededObj, 1, ticket);
	
			if (!parentNode.getInfo().getSuccess()) 
					continue;
			
			CatalogVo vo=new CatalogVo();
			//得到长编
			vo.setSummary(s);
			vo.setCatalog((Catalog)parentNode.getData().get(0).getNode());
			catalogVos.add(vo);
		}
		
		List<Map<String, Object>> catalogList = catalogService.getCatalogs(sortField, sortAsc, neededObj, lv, ticket, resourceType, this.getEntityName());
		templateData.put("catalogs", catalogList);
		templateData.put("catalogVos", catalogVos);
		templateData.put("title", "长编");
		// 初始化模板引擎
		FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("/"), response,"上海申通地铁集团修志长编文档");
		Writer out;
		try {
			// 重点：一定要注意编码格式，漏写编码格式将导致word无法打开（xml非法字符）
			out = new BufferedWriter(new OutputStreamWriter(
					response.getOutputStream(), "utf-8"));
			FreeMarkerUtils.createDoc(templateData, out, "templates/catalog-summarys-mht.ftl");
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
		
	
	/**
	 * 导出单张长编
	 * @param id
	 * @param type
	 * @param sortField
	 * @param sortAsc
	 * @param neededObj
	 * @param ticket
	 * @param request
	 * @param response
	 * @return
	 */

	@RequestMapping(value="/exportSummary")
	@ResponseBody
	public String exportSummary(
			@RequestParam("id") Integer id,
			@RequestParam(value = "type", required = false, defaultValue = "") String type,
			@RequestParam(value = "sortField", required = false, defaultValue = "") String sortField,
			@RequestParam(value = "sortAsc", required = false, defaultValue = "asc") String sortAsc,
			@RequestParam(value = "objFilter", required = false, defaultValue = "") String neededObj,
			@RequestParam(value = "ticket", required = true) String ticket,
			HttpServletRequest request, HttpServletResponse response){
		Summary summary = get(id+"");
		
		/** 模板引擎所需要的数据Map */
		Map<String, Object> templateData = new HashMap<String, Object>();
		
		ReturnObj<List<RelatedNode<IDefaultModel,Integer>>> node = getParentNode(id, sortField, sortAsc, neededObj, 1, ticket);
		
		if (node.getInfo().getSuccess()) {
			CatalogVo vo=new CatalogVo();
			vo.setSummary(summary);
			vo.setCatalog((Catalog)node.getData().get(0).getNode());
			templateData.put("vo",vo);
			FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("/"), response,summary.getCode());
			// 重点：一定要注意编码格式，漏写编码格式将导致word无法打开（xml非法字符）
			Writer out;
			try {
				out = new BufferedWriter(new OutputStreamWriter(
						response.getOutputStream(), "utf-8"));
				FreeMarkerUtils.createDoc(templateData, out, "templates/summary-mht.ftl");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	/**
	 * 导出全部长编
	 * @param ids
	 * @param type
	 * @param sortField
	 * @param sortAsc
	 * @param neededObj
	 * @param lv
	 * @param ticket
	 * @param resourceType
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exportAll")
	@ResponseBody
	public String exportAll(
					@RequestParam("ids") String ids,
					@RequestParam(value = "type", required = false, defaultValue = "") String type,
					@RequestParam(value = "sortField", required = false, defaultValue = "") String sortField,
					@RequestParam(value = "sortAsc", required = false, defaultValue = "asc") String sortAsc,
					@RequestParam(value = "objFilter", required = false, defaultValue = "") String neededObj,
					@RequestParam(value = "lv", required = false, defaultValue = "-1") int lv,
					@RequestParam(value = "ticket", required = true) String ticket,
					@RequestParam(value = "resourceType", required = true) String resourceType,
					HttpServletRequest request, HttpServletResponse response){

		List<Integer> catalogIds=new ArrayList<Integer>();
		for (String id : StringUtils.split(ids,",")) {
			catalogIds.add(Integer.parseInt(id));
		}
		String summaryIds = (String)ReflectUtil.executeMethod("catalog", "findByCardsOrSummarys", 
                new Class[] { List.class, String.class, String.class }, new Object[] { catalogIds, "catalog", this.getEntityName()});

		/** 模板引擎所需要的数据Map */
		Map<String, Object> templateData = new HashMap<String, Object>();
		if (!StringUtil.isNull(summaryIds)) {
			SingleQueryParams sqp = SingleParamsConvertUtil.getQueryParams(this.getEntityClass(), request);
			sqp.addSort("operateTime", "asc");
			sqp.addData("status", "finish");
			sqp.addData("id_in", summaryIds );
			ReturnObj<List<IDefaultModel>> returnObj = getBasicCrudService().find(sqp);
			if (!returnObj.getInfo().getSuccess()) 
				return null;
			List<CatalogVo> catalogVos=new ArrayList<CatalogVo>();
			
			for (IDefaultModel data : returnObj.getData()) {
				Summary s=(Summary) data;
				//查询该长编父节点
				ReturnObj<List<RelatedNode<IDefaultModel, Integer>>> parentNode = getParentNode(s.getId(), sortField, sortAsc, neededObj, 1, ticket);
		
				if (!parentNode.getInfo().getSuccess()) 
						continue;
				
				CatalogVo vo=new CatalogVo();
				//得到长编
				vo.setSummary(s);
				vo.setCatalog((Catalog)parentNode.getData().get(0).getNode());
				catalogVos.add(vo);
			}
			List<Map<String, Object>> catalogList = catalogService.getCatalogs(sortField,
					sortAsc, neededObj, lv, ticket, resourceType, this.getEntityName());
			templateData.put("catalogs", catalogList);
			templateData.put("catalogVos", catalogVos);
			templateData.put("title", "长编");
			// 初始化模板引擎
			FreeMarkerUtils.initFreeMarker(request.getSession().getServletContext().getRealPath("/"), response,"上海申通地铁集团修志长编文档");
			Writer out;
			try {
				// 重点：一定要注意编码格式，漏写编码格式将导致word无法打开（xml非法字符）
				out = new BufferedWriter(new OutputStreamWriter(
						response.getOutputStream(), "utf-8"));
				FreeMarkerUtils.createDoc(templateData, out, "templates/catalog-summarys-mht.ftl");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
}
